<template>
  <ContentWrap>
    <!-- 搜索区域使用卡片包裹 -->
    <el-card class="search-wrapper">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-medium">线索筛选</span>
          <el-button
            :type="isSearchExpanded ? 'default' : 'primary'"
            size="small"
            @click="toggleSearch"
          >
            <template #icon>
              <Icon :icon="isSearchExpanded ? 'ep:arrow-up' : 'ep:arrow-down'" />
            </template>
            {{ isSearchExpanded ? '收起筛选' : '展开筛选' }}
          </el-button>
        </div>
      </template>
      
      <el-collapse-transition>
        <div v-show="isSearchExpanded">
          <el-form
            :model="queryParams"
            ref="queryFormRef"
            :inline="true"
            label-width="80px"
          >
            <div class="grid grid-cols-4 gap-4">
              <el-form-item label="姓名" prop="name">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入姓名"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input
                  v-model="queryParams.phone"
                  placeholder="请输入手机号"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="线索来源" prop="source">
                <el-input
                  v-model="queryParams.source"
                  placeholder="请输入来源"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="城市" prop="city">
                <el-input
                  v-model="queryParams.city"
                  placeholder="请输入城市"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="ip" prop="ip">
                <el-input
                  v-model="queryParams.ip"
                  placeholder="请输入ip"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="备注" prop="notes">
                <el-input
                  v-model="queryParams.notes"
                  placeholder="请输入备注"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="线索状态" prop="status" class="col-span-2">
                <el-select
                  v-model="queryParams.status"
                  placeholder="请选择线索状态"
                  clearable
                  class="!w-full"
                >
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.WEIYI_LEADS)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="上报时间" prop="createTime" class="col-span-2">
                <el-date-picker
                  v-model="queryParams.createTime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  type="daterange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                  class="!w-full"
                />
              </el-form-item>
              <el-form-item label="部门ID" prop="deptId">
                <el-input
                  v-model="queryParams.deptId"
                  placeholder="请输入部门ID"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="客户ID" prop="assignedTo">
                <el-input
                  v-model="queryParams.assignedTo"
                  placeholder="请输入客户ID"
                  clearable
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
            </div>
          </el-form>
          
          <div class="flex justify-end mt-4">
            <el-button type="primary" @click="handleQuery">
              <Icon icon="ep:search" class="mr-5px" /> 搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" class="mr-5px" /> 重置
            </el-button>
          </div>
        </div>
      </el-collapse-transition>
    </el-card>
  </ContentWrap>

  <!-- 操作按钮区 -->
  <ContentWrap class="mt-4">
    <div class="flex justify-between mb-4">
      <div class="flex gap-2">
        <el-button
          type="primary"
          @click="openForm('create')"
          v-hasPermi="['weiyi:leads:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增线索
        </el-button>
        <el-button
          type="success"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['weiyi:leads:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出数据
        </el-button>
        <el-button
          type="primary"
          plain
          @click="handleAssign"
          :loading="assignLoading"
          v-hasPermi="['weiyi:leads:autofenpei']"
        >
          <Icon icon="ep:share" class="mr-1" />
          自动分配
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleAssign"
          :loading="assignLoading"
          v-hasPermi="['weiyi:leads:loadfenpei']"
        >
          <Icon icon="ep:refresh" class="mr-1" />
          重新分配
        </el-button>
        <el-button
          type="success"
          plain
          @click="openImport"
          v-hasPermi="['weiyi:leads:import']"
        >
          <Icon icon="ep:upload-filled" class="mr-1" />
          导入数据
        </el-button>
        <el-button
          type="warning"
          plain
          @click="handleAssignSelected"
          :disabled="selectedIds.length === 0"
          v-hasPermi="['weiyi:leads:assign']"
        >
          <Icon icon="ep:share" class="mr-1" />
          手动分配
        </el-button>
      </div>
      <el-tag type="info">共 {{ total }} 条线索</el-tag>
    </div>

    <!-- 数据表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        style="width: 100%"
        @row-click="tableRowClick"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="基本信息" min-width="50">
          <template #default="{ row }">
            <div class="flex items-center">
              <el-avatar :size="40" class="mr-3">{{ row.name?.charAt(0) }}</el-avatar>
              <div>
                <div class="font-medium">{{ row.name }}</div>
                <div class="text-gray-500 text-sm">{{ row.phone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="来源信息" min-width="50">
          <template #default="{ row }">
            <div>
              <div>来源：{{ row.source }}</div>
              <div class="text-gray-500 text-sm mt-1">
                <Icon icon="ep:location" class="mr-1" />{{ row.city }}
                <el-divider direction="vertical" />
                <Icon icon="ep:connection" class="mr-1" />{{ row.ip }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="120">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.WEIYI_LEADS" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          :formatter="dateFormatter"
          width="180"
        />
        <el-table-column 
          label="备注" 
          prop="notes" 
          min-width="150" 
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span class="text-gray-500">{{ row.notes || '暂无备注' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                :type="row.hasAssignLogs ? 'danger' : 'primary'"
                link
                @click="handleViewAssignLogs(row)"
                @click.stop="handleViewAssignLogs(row)"
                v-hasPermi="['weiyi:leads:view-logs']"
              >
                <Icon icon="ep:info-filled" />
                分配记录
              </el-button>
              <el-button
                type="primary"
                link
                @click.stop="openForm('update', row.id)"
                v-hasPermi="['weiyi:leads:update']"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                @click.stop="handleDelete(row.id)"
                v-hasPermi="['weiyi:leads:delete']"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="mt-4">
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <LeadsForm ref="formRef" @success="getList" />

  <!-- 右侧详情抽屉 -->
  <el-drawer
    v-model="drawerVisible"
    title="线索详情"
    size="500px"
    :destroy-on-close="true"
  >
    <template #header>
      <div class="flex items-center justify-between w-full pr-4">
        <span class="text-lg font-medium">线索详情</span>
        <dict-tag :type="DICT_TYPE.WEIYI_LEADS" :value="currentLead?.status || ''" />
      </div>
    </template>

    <div v-if="currentLead" class="p-4">
      <!-- 基本信息 -->
      <div class="mb-6">
        <div class="flex items-center mb-4">
          <el-avatar :size="60" class="mr-4">{{ currentLead.name?.charAt(0) }}</el-avatar>
          <div>
            <h3 class="text-xl font-medium mb-1">{{ currentLead.name }}</h3>
            <p class="text-gray-500">{{ currentLead.phone }}</p>
          </div>
        </div>
        
        <el-descriptions :column="1" border>
          <el-descriptions-item label="来源">{{ currentLead.source }}</el-descriptions-item>
          <el-descriptions-item label="城市">{{ currentLead.city }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentLead.ip }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ dayjs(currentLead.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            <div class="whitespace-pre-wrap">{{ currentLead.notes || '暂无备注' }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 跟进记录 -->
      <div class="mb-6">
        <div class="flex justify-between items-center mb-4">
          <h4 class="text-lg font-medium">跟进记录</h4>
          <el-button type="primary" @click="openFollowUpDialog">
            <Icon icon="ep:plus" class="mr-5px" /> 添加跟进
          </el-button>
        </div>
        
        <el-timeline>
          <el-timeline-item
            v-for="record in followUpList"
            :key="record.id"
            :timestamp="dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss')"
            :type="record.type"
          >
            <div class="follow-up-item">
              <div class="flex items-center gap-2 mb-2">
                <el-tag :type="getFollowTypeTag(record.type)">
                  {{ getFollowTypeLabel(record.type) }}
                </el-tag>
                <span class="text-gray-500 text-sm">跟进人: {{ record.creatorName }}</span>
              </div>
              <div class="content-section">
                <div class="mb-2">
                  <span class="label">跟进内容:</span>
                  <span class="content">{{ record.content }}</span>
                </div>
                <div class="text-gray-500 text-sm">
                  <div class="mb-1">
                    <span class="label">备注:</span>
                    <span class="content">{{ record.notes }}</span>
                  </div>
                  <div>
                    <span class="label">时间:</span>
                    <span class="content">{{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>

      <!-- 分配线索 -->
      <!-- <div class="mb-6">
        <h4 class="text-lg font-medium mb-4">分配线索</h4>
        <el-form :model="assignForm" label-width="80px">
          <el-form-item label="跟进人">
            <el-select v-model="assignForm.userId" class="w-full">
              <el-option
                v-for="user in userList"
                :key="user.id"
                :label="user.name"
                :value="user.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAssign">确认分配</el-button>
          </el-form-item>
        </el-form>
      </div> -->
    </div>
  </el-drawer>

  <!-- 添加跟进记录弹窗 -->
  <el-dialog
    v-model="followUpDialogVisible"
    title="添加跟进记录"
    width="500px"
  >
    <el-form :model="followUpForm" label-width="80px">
      <el-form-item label="跟进类型" required>
        <el-select v-model="followUpForm.type" class="w-full">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.WEIYI_LEADS_FOLLOW_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="跟进内容" required>
        <el-input
          v-model="followUpForm.content"
          type="textarea"
          :rows="4"
          placeholder="请输入跟进内容"
        />
      </el-form-item>
      <el-form-item label="备注" required>
        <el-input
          v-model="followUpForm.notes"
          type="textarea"
          :rows="4"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="followUpDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleAddFollowUp">确认</el-button>
    </template>
  </el-dialog>

  <!-- 线索导入对话框 -->
  <LeadsImportForm ref="importFormRef" @success="getList" />

  <!-- 分配弹窗 -->
  <AssignDialog 
    v-model="assignDialogVisible"
    :selectedIds="selectedIds"
    @success="handleAssignSuccess"
  />

  <!-- 分配记录弹窗 -->
  <el-dialog
    v-model="assignLogsVisible"
    title="分配记录"
    width="700px"
  >
    <div v-loading="logsLoading" class="assign-logs-container">
      <!-- 统计信息 -->
      <div class="assign-stats mb-4">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-label">分配员工次数</div>
              <div class="stat-value">{{ getAssignTypeCount(2) }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-label">分配部门次数</div>
              <div class="stat-value">{{ getAssignTypeCount(1) }}</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-label">分配API次数</div>
              <div class="stat-value">{{ getAssignTypeCount(3) }}</div>
            </div>
          </el-col>
        </el-row>
      </div>

      <el-timeline>
        <el-timeline-item
          v-for="log in assignLogs"
          :key="log.id"
          :timestamp="formatDateTime(log.createTime)"
          :type="getAssignTypeTag(log.assignType)"
        >
          <div class="flex flex-col gap-1">
            <span class="font-medium">
              {{ getAssignTypeLabel(log.assignType) }}：
              <template v-if="log.assignType === 1">
                {{ log.targetName || log.targetId }}
              </template>
              <template v-else-if="log.assignType === 2">
                {{ log.targetName || log.targetId }}
              </template>
              <template v-else>
                {{ log.apiName || log.apiCode || log.targetId }}
              </template>
            </span>
            <span class="text-gray-500 text-sm">
              分配时间：{{ formatDateTime(log.createTime) }}
            </span>
          </div>
        </el-timeline-item>
      </el-timeline>
      
      <div v-if="assignLogs.length === 0" class="text-center py-4 text-gray-500">
        暂无分配记录
      </div>
      <div class="assign-logs-footer">
        总分配次数：<span class="text-primary font-medium">{{ assignLogs.length }}</span> 次
      </div>
    </div>
  </el-dialog>

  <!-- 自动分配报告弹窗 -->
  <el-dialog
    v-model="assignReportVisible"
    title="自动分配报告"
    width="800px"
    destroy-on-close
  >
    <div class="whitespace-pre-wrap font-mono">{{ assignReport }}</div>
    <template #footer>
      <el-button type="primary" @click="assignReportVisible = false">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { LeadsApi, LeadsVO } from '@/api/weiyi/leads'
import type { AssignLogVO } from '@/api/weiyi/leads'
import LeadsForm from './LeadsForm.vue'
import dayjs from 'dayjs'
import { ref, reactive, onMounted } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { getFollowUpList, createFollowUp, type FollowUpVO } from '@/api/weiyi/leads/followUp'
import { formatDateTime } from '@/utils/formatTime'
import LeadsImportForm from './LeadsImportForm.vue'
import AssignDialog from '@/components/AssignDialog/AssignDialog.vue'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'

/** CRM线索 列表 */
defineOptions({ name: 'Leads' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ExtendedLeadsVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 50,
  name: undefined,
  phone: undefined,
  source: undefined,
  city: undefined,
  ip: undefined,
  notes: undefined,
  status: undefined,
  createTime: [],
  deptId: undefined,
  assignedTo: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const assignLoading = ref(false)

// 选中的数据ID数组
const selectedIds = ref<number[]>([])

// 分配弹窗显示状态
const assignDialogVisible = ref(false)

// 缓存对象，用于存储线索ID与是否有分配记录的映射
const assignLogsCache = reactive<Record<number, boolean>>({})

// 扩展LeadsVO类型
interface ExtendedLeadsVO extends LeadsVO {
  hasAssignLogs?: boolean;
}

// 首先添加报告弹窗相关的状态
const assignReportVisible = ref(false)
const assignReport = ref('')

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await LeadsApi.getLeadsPage(queryParams)
    list.value = data.list
    total.value = data.total
    
    // 应用已有的缓存数据
    applyAssignLogsCache()
    
    // 主动查询当前页所有记录的分配状态
    await checkAssignLogsForList()
  } finally {
    loading.value = false
  }
}

// 添加应用缓存的函数
const applyAssignLogsCache = () => {
  if (!list.value || list.value.length === 0) return
  
  list.value.forEach(item => {
    if (assignLogsCache[item.id] !== undefined) {
      item.hasAssignLogs = assignLogsCache[item.id]
    }
  })
}

// 添加检查单个线索的函数
const checkSingleAssignLog = async (row: ExtendedLeadsVO) => {
  // 如果已经有缓存，直接使用缓存
  if (assignLogsCache[row.id] !== undefined) {
    row.hasAssignLogs = assignLogsCache[row.id]
    return
  }
  
  try {
    const logs = await LeadsApi.getAssignLogs(row.id)
    const hasLogs = logs && logs.length > 0
    // 更新缓存和UI
    assignLogsCache[row.id] = hasLogs
    row.hasAssignLogs = hasLogs
  } catch (error) {
    console.error(`检查线索 ${row.id} 的分配记录失败`, error)
    assignLogsCache[row.id] = false
    row.hasAssignLogs = false
  }
}

// 修改检查列表中所有线索的分配记录状态函数
const checkAssignLogsForList = async () => {
  if (!list.value || list.value.length === 0) return
  
  try {
    // 找出未缓存的线索ID
    const uncachedItems = list.value.filter(item => assignLogsCache[item.id] === undefined)
    
    // 如果所有项都已缓存，直接应用缓存结果
    if (uncachedItems.length === 0) {
      list.value.forEach(item => {
        item.hasAssignLogs = assignLogsCache[item.id] || false
      })
      return
    }
    
    // 获取未缓存的ID列表
    const uncachedIds = uncachedItems.map(item => item.id)
    
    // 使用后端提供的批量查询API
    try {
      // 调用批量查询API
      const result = await LeadsApi.batchCheckAssignLogs(uncachedIds)
      if (result && Array.isArray(result)) {
        // 更新缓存和UI
        result.forEach(item => {
          assignLogsCache[item.id] = item.hasLogs
          const lead = list.value.find(l => l.id === item.id)
          if (lead) {
            lead.hasAssignLogs = item.hasLogs
          }
        })
        return
      }
    } catch (error) {
      console.error('批量查询分配记录失败，回退到单个查询', error)
    }
    
    // 如果批量API失败，回退到单个查询
    const promises = uncachedItems.map(async (item) => {
      try {
        const logs = await LeadsApi.getAssignLogs(item.id)
        const hasLogs = logs && logs.length > 0
        // 更新缓存
        assignLogsCache[item.id] = hasLogs
        // 更新UI
        item.hasAssignLogs = hasLogs
      } catch (error) {
        console.error(`检查线索 ${item.id} 的分配记录失败`, error)
        assignLogsCache[item.id] = false
        item.hasAssignLogs = false
      }
    })
    
    // 等待所有请求完成
    await Promise.all(promises)
  } catch (error) {
    console.error('检查分配记录状态失败', error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await LeadsApi.deleteLeads(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await LeadsApi.exportLeads(queryParams)
    download.excel(data, 'CRM线索.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 搜索区展开收起 */
const isSearchExpanded = ref(true)
const toggleSearch = () => {
  isSearchExpanded.value = !isSearchExpanded.value
}

/** 右侧抽屉相关 */
const drawerVisible = ref(false)
const currentLead = ref<ExtendedLeadsVO | null>(null)
const followUpList = ref<FollowUpVO[]>([])

const followUpDialogVisible = ref(false)
const followUpForm = reactive({
  content: '',
  type: 'phone',
  notes: '',
  leadsId: null as number | null
})

// 加载跟进记录列表
const loadFollowUpList = async (leadsId: number) => {
  try {
    const res = await getFollowUpList(leadsId)
    console.log('跟进记录返回数据:', res) 
    // 直接使用返回的数据，因为后端返回的就是 {list, total} 格式
    followUpList.value = res.list
  } catch (error) {
    console.error('获取跟进记录错误:', error)
    message.error('获取跟进记录失败')
  }
}

// 添加跟进记录
const handleAddFollowUp = async () => {
  if (!followUpForm.content.trim()) {
    message.warning('请输入跟进内容')
    return
  }
  if (!followUpForm.notes.trim()) {
    message.warning('请输入备注信息')
    return
  }
  if (!followUpForm.leadsId) {
    message.warning('线索ID不能为空')
    return
  }
  
  try {
    await createFollowUp({
      leadsId: followUpForm.leadsId,
      content: followUpForm.content,
      type: followUpForm.type,
      notes: followUpForm.notes
    })
    followUpDialogVisible.value = false
    message.success('添加跟进记录成功')
    // 重新加载跟进记录列表
    if (currentLead.value?.id) {
      await loadFollowUpList(currentLead.value.id)
    }
  } catch (error) {
    message.error('添加跟进记录失败')
  }
}

/** 打开详情抽屉 */
const openDrawer = async (row: ExtendedLeadsVO) => {
  currentLead.value = row
  drawerVisible.value = true
  if (row.id) {
    await loadFollowUpList(row.id)
  }
}

/** 修改表格行点击事件，在点击行时检查分配记录 */
const tableRowClick = async (row: ExtendedLeadsVO) => {
  // 在打开抽屉前检查分配记录状态
  if (assignLogsCache[row.id] === undefined) {
    await checkSingleAssignLog(row)
  }
  openDrawer(row)
}

/** 打开跟进记录弹窗 */
const openFollowUpDialog = () => {
  followUpForm.content = ''
  followUpForm.type = 'phone'
  followUpForm.notes = ''
  followUpForm.leadsId = currentLead.value?.id || null
  followUpDialogVisible.value = true
}

/** 初始化 **/
onMounted(() => {
  getList()
})

const getFollowTypeLabel = (type: string) => {
  const dict = getIntDictOptions(DICT_TYPE.WEIYI_LEADS_FOLLOW_TYPE).find(
    (item) => item.value === type
  )
  return dict?.label || type
}

const getFollowTypeTag = (type: string) => {
  switch (type) {
    case 'phone':
      return 'primary'
    case 'wechat':
      return 'success'
    case 'email':
      return 'warning'
    default:
      return 'info'
  }
}

/** 修改自动分配处理函数 */
const handleAssign = async () => {
  try {
    // 添加确认提示
    await message.confirm('确认要执行自动分配操作吗？')
    
    assignLoading.value = true
    const response = await LeadsApi.autoAssignLeads()
    
    if (response) {
      // 显示分配报告
      assignReport.value = response
      assignReportVisible.value = true
      // 刷新列表
      await getList()
      message.success('自动分配完成')
    } else {
      message.error('自动分配失败：未收到响应数据')
    }
  } catch (error: any) {
    if (error === 'cancel') return // 用户取消操作，不显示错误
    console.error('自动分配失败:', error)
    message.error('自动分配失败：' + (error?.message || '未知错误'))
  } finally {
    assignLoading.value = false
  }
}

// 导入相关
const importFormRef = ref()
const openImport = () => {
  importFormRef.value.open()
}

// 处理选中数据分配
const handleAssignSelected = () => {
  if (selectedIds.value.length === 0) {
    message.warning('请至少选择一条数据')
    return
  }
  assignDialogVisible.value = true
}

// 表格多选框选择事件
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分配成功回调
const handleAssignSuccess = () => {
  // 重新加载列表数据
  getList()
  // 清空选中
  selectedIds.value = []
}

/** 分配记录相关 */
const assignLogsVisible = ref(false)
const assignLogs = ref<AssignLogVO[]>([])
const logsLoading = ref(false)

// 查看分配记录
const handleViewAssignLogs = async (row: ExtendedLeadsVO) => {
  try {
    logsLoading.value = true
    
    // 获取分配记录
    assignLogs.value = await LeadsApi.getAssignLogs(row.id)
    
    // 标记该行数据有分配记录并更新缓存
    const hasLogs = assignLogs.value && assignLogs.value.length > 0
    row.hasAssignLogs = hasLogs
    assignLogsCache[row.id] = hasLogs
    
    // 所有数据准备好后再打开弹窗
    assignLogsVisible.value = true
  } catch (error) {
    message.error('获取分配记录失败')
  } finally {
    logsLoading.value = false
  }
}

/** 获取分配类型标签样式 */
const getAssignTypeTag = (type: number) => {
  switch (type) {
    case 1: return 'primary'   // 部门
    case 2: return 'success'   // 员工
    case 3: return 'warning'   // API客户
    default: return 'info'
  }
}

/** 获取分配类型文本 */
const getAssignTypeLabel = (type: number) => {
  switch (type) {
    case 1: return '分配给部门'
    case 2: return '分配给员工'
    case 3: return '分配给API客户'
    default: return '未知类型'
  }
}

/** 获取指定类型的分配次数 */
const getAssignTypeCount = (type: number) => {
  return assignLogs.value.filter(log => log.assignType === type).length
}
</script>

<style lang="scss" scoped>
.search-wrapper :deep(.el-card__header) {
  padding: 14px 20px;
}

.search-wrapper :deep(.el-card__body) {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 16px;
}

.follow-up-item {
  padding: 16px;
  background: #f5f7fa;
  border-left: 4px solid var(--el-color-primary);
  border-radius: 4px;
}

/* 添加过渡动画 */
.el-collapse-transition {
  transition: all 0.3s ease-in-out;
}

.whitespace-pre-wrap {
  white-space: pre-wrap;
}

.el-timeline {
  padding: 20px;
  margin-bottom: 40px;
}

:deep(.el-timeline-item__node) {
  background-color: var(--el-color-primary);
}

:deep(.el-timeline-item__tail) {
  border-left-color: var(--el-border-color-lighter);
}

.el-timeline-item {
  padding-bottom: 20px;
}

.el-tag {
  text-transform: capitalize;
}

.content-section {
  padding-left: 8px;
}

.label {
  display: inline-block;
  margin-right: 8px;
  font-weight: 500;
  color: #606266;
}

.content {
  color: #303133;
}

.assign-logs-container {
  position: relative;
  min-height: 200px;
}

.assign-logs-footer {
  position: absolute;
  right: 0;
  bottom: -20px;
  padding: 8px 16px;
  color: var(--el-text-color-secondary);
}

.text-primary {
  color: var(--el-color-primary);
}

.assign-stats {
  padding: 16px;
  background-color: var(--el-fill-color-light);
  border-radius: 8px;
}

.stat-item {
  padding: 12px;
  text-align: center;
  background-color: var(--el-bg-color);
  border-radius: 6px;
  box-shadow: 0 2px 4px rgb(0 0 0 / 5%);
}

.stat-label {
  margin-bottom: 8px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-color-primary);
}
</style>